import type { App, Plugin } from 'vue'
import constant from '@/utils/constant'
import { useAppStore } from '@/store/modules/app'
import cache from '@/utils/cache'
import moment from 'moment'

// 把路径转换成驼峰命名
export const pathToCamel = (path: string): string => {
    return path.replace(/\/(\w)/g, (all, letter) => letter.toUpperCase())
}

// 是否外链
export const isExternalLink = (url: string): boolean => {
    return /^(https?:|\/\/|http?:|\/\/|^{{\s?apiUrl\s?}})/.test(url)
}

// 替换外链参数
export const replaceLinkParam = (url: string): string => {
    return url.replace('{{apiUrl}}', constant.apiUrl)
}

// 转换文件大小格式
export const convertSizeFormat = (size: number): string => {
    const unit = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
    let index = Math.floor(Math.log(size) / Math.log(1024))
    let newSize = size / Math.pow(1024, index)

    // 保留的小数位数
    return newSize.toFixed(2) + ' ' + unit[index]
}

// 获取svg图标(id)列表
export const getIconList = (): string[] => {
    const rs: string[] = []
    const list = document.querySelectorAll('svg symbol[id^="icon-"]')
    for (let i = 0; i < list.length; i++) {
        rs.push(list[i].id)
    }
    return rs
}

// 获取字典Label
export const getDictLabel = (dictList: any[], dictType: string, dictValue: string) => {
    const type = dictList.find((element: any) => element.dictType === dictType)
    if (type) {
        const val = type.dataList.find((element: any) => element.dictValue === dictValue + '')
        if (val) {
            return val.dictLabel
        } else {
            return dictValue
        }
    } else {
        return dictValue
    }
}

// 获取字典Label样式
export const getDictLabelClass = (dictList: any[], dictType: string, dictValue: string): string => {
    const type = dictList.find((element: any) => element.dictType === dictType)
    if (type) {
        const val = type.dataList.find((element: any) => element.dictValue === dictValue + '')
        if (val) {
            return val.labelClass
        } else {
            return ''
        }
    } else {
        return ''
    }
}

export const getDictLabelList = (dictType: string, dictValue: string): string => {
    if (Number.isInteger(dictValue)) {
        dictValue = dictValue + ''
    }

    if (!dictValue) {
        return ''
    }

    const appStore = useAppStore()

    let result = ''
    dictValue.split(',').forEach(value => {
        const classStyle = getDictLabelClass(appStore.dictList, dictType, value)
        const label = getDictLabel(appStore.dictList, dictType, value)

        if (classStyle) {
            result += `<span class="el-tag el-tag--${classStyle} el-tag--${appStore.componentSize}">${label}</span>&nbsp;`
        } else {
            result += label + '&nbsp;'
        }
    })

    return result
}

// 获取字典数据列表
export function getDictDataList(dictList: any[], dictType: string) {
    const type = dictList.find((element: any) => element.dictType === dictType)
    if (type) {
        return type.dataList
    } else {
        return []
    }
}

// 全局组件安装
export const withInstall = <T>(component: T, alias?: string) => {
    const comp = component as any
    comp.install = (app: App) => {
        app.component(comp.name || comp.displayName, component)
        if (alias) {
            app.config.globalProperties[alias] = component
        }
    }
    return component as T & Plugin
}

export const fullBaseURL = () => {
    const currentProtocol = window.location.protocol; // 获取当前协议，例如：http: 或 https:
    const currentHostname = window.location.hostname; // 获取当前域名，例如：www.example.com
    const currentPort = window.location.port; // 获取当前端口，例如：8080（如果没有指定端口，则默认是80）
    const baseURL = currentProtocol + "//" + currentHostname + (currentPort ? ":" + currentPort : "");
    return baseURL;
}

export const fullBaseAPI_URL = () => {
    return `${fullBaseURL() + import.meta.env.VITE_API_URL}`;
}

// 文件上传地址
export const uploadUrl = () => {
    return `${fullBaseAPI_URL()}/sys/file/upload?access_token=${cache.getToken()}&base_path=${fullBaseAPI_URL()}`
}

/**
 * 身份证合法性
 * @param idCard 身份证 15 / 18
 * @returns { birthday? }  出生年月日 {YYYY-DD-MM} 或者 false 
 */
export const checkIdCard = (idCard: string) => {
    //15位转18位身份证号  
    let changeFivteenToEighteen = function (card) {
        if (card.length === 15) {
            var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
            var cardTemp = 0, i;
            card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
            for (i = 0; i < 17; i++) {
                cardTemp += card.substr(i, 1) * arrInt[i];
            }
            card += arrCh[cardTemp % 11];
            return card;
        }
        return card;
    };

    const card = changeFivteenToEighteen(idCard)

    var checkProv = function (val) {
        var pattern = /^[1-9][0-9]/;
        var provs = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门" };
        if (pattern.test(val)) {
            if (provs[val]) {
                return true;
            }
        }
        return false;
    }
    var checkDate = function (val) {
        var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
        if (pattern.test(val)) {
            var year = val.substring(0, 4);
            var month = val.substring(4, 6);
            var date = val.substring(6, 8);
            var date2 = new Date(year + "-" + month + "-" + date);
            if (date2 && date2.getMonth() == (parseInt(month) - 1)) {
                return true;
            }
        }
        return false;
    }
    var checkCode = function (val) {
        var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var code = val.substring(17);
        if (p.test(val)) {
            var sum = 0;
            for (var i = 0; i < 17; i++) {
                sum += val[i] * factor[i];
            }
            if (parity[sum % 11] == code.toUpperCase()) {
                return true;
            }
        }
        return false;
    }
    var checkID = function (val) {
        if (checkCode(val)) {
            var date = val.substring(6, 14);
            if (checkDate(date)) {
                if (checkProv(val.substring(0, 2))) {
                    return true;
                }
            }
        }
        return false;
    }
    if (checkID(card)) {
        let birthday = card.substring(6, 14)
        birthday = `${birthday.substring(0, 4)}-${birthday.substring(4, 6)}-${birthday.substring(6, 8)}`
        return {
            birthday
        }
    } else {
        return false
    }
}

/**
 * 获取最近6个月
 */
export const getLastSixMonths = () => {
    const lastSixMonths = [];
    for (let i = 1; i <= 6; i++) {
        // 在循环外定义不会刷新moment，需要放在循环内每次生成新的moment
        /*
            导致问题：
            比如：当前月份12 被减数为索引
                12 - 1 = 11 
                11 - 2 = 9
                9 - 3 = 6
            正确为：
                12 - 1 = 11
                12 - 2 = 10
                12 - 3 = 9
        */
        const currentDate = moment();
        const monthDate = currentDate.subtract(i, 'months');
        lastSixMonths.push(monthDate.format('MM'));
    }
    return lastSixMonths;
}
/**
 * 获取16进制RGB颜色
 */
export function generateRandomHexColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}